// pages/getPackets/packets.js 红包奖励
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isLoading: 1,//是否显示加载中图标
    share_title:'',//分享的标题
    static_url_http:'',//资源文件地址
    share_img:'../../images/red-packet/share-img.png',
    enve_page_top_adv_is_show: 0,//控制广告位的显示和隐藏个
    page: 1,
    pageFile: 1,//初始化文档页码
    winHeight: 510,//获取手机屏幕的高度
    hosList: [],//存储列表数据
    listPage: 1,//初始化页面
    imgUrls: [
      {
        "img": "../../images/red-packet/user.jpg", "desc_time": "6秒前提现", 'content': "现金66.6元"
      }, {
        "img": "../../images/red-packet/user.jpg", "desc_time": "6秒前提现", 'content': "现金66.6元"
      }, {
        "img": "../../images/red-packet/user.jpg", "desc_time": "6秒前提现", 'content': "现金66.6元"
      },

    ],//存储轮播假数据
    shareUserList: [],//邀请用户列表
    recommendList: [],//获取文档列表
    enve_id: '',//当前红包ID
    uid: "",//用户id
    playRobots: [],
    title: "",//提示表示
    content: '',//红包内容
    enve_share_info_title: "天天拆红包·领百元现金",
    enve_share_info_border_tips: '可提现',
    successEnve: '0.00',//领取成功弹层显示金额
    successLeftTips: '还需要邀请',//领取成功弹层显示需要人数的提示内容
    successEnveNum: '0',//领取成功需要多少个人
    successRightTips: '个好友领取才可以拆开哦',//领取成功弹层显示需要人数的提示内容

    is_opend: 0, //红包是否已经打开 默认为0 表示未打开
    balance: '0.00',//用户已领导的总余额
    head_img: '',
    enve_box_title: '您有一个超级大红包未拆开',
    successGainTips: '恭喜你获得',//用户拆开红包后点击立即领取成功后显示的问你自
    successGainEnve: '0.00',//用户拆开红包后点击立即领取成功后显示的红包金额
    successGainLeftTips: '还需要邀请',//用户红包被拆开后点击领取后的文字
    successGainEnveNum: '0',//用户红包被拆开后点击立即领取显示的拆包人数
    successGainRightTips: '个好友领取才可以拆开哦',//用户红包被拆开后点击立即领取后显示的文字
    shareGainUserList: [],// 用户红包被拆开后点击立即领取后显示的用户列表
    isReceiveRedPacketShow: 0, //是否显示去分享谈层 默认0不显示 1表示显示
    shareGainEnveId: '',//红包拆开后点击立即领取成功后的红包ID 用于分享
    shareGainUid: '',//拆开红包点击立即领取成功后的UID 用于分享
    shareFriendsBtn: "邀请好友领红包",
    group_share_isopen: 0, //是否开启分享到群
    group_share_num: 0,//需要分享到群的数量
    group_share_show: 0,//是否显示群分享模块
    advSoltIcon: ""
  },
  // 点击顶部导航跳转广告详情
  jumpDetail: function (e) {
    var advType = e.currentTarget.dataset.type_detail;
    console.log(advType);
    if (advType.adv_type == 3) {
      wx.navigateToMiniProgram({
        appId: advType.app_id.toString(),
        path: advType.page.toString(),
        extraData: advType.sence.toString(),
        complete(res) {
          console.log(res)
        }
      });
    } else if (advType.adv_type == 4) {
      var subject_id = advType.adv_id;
      wx.navigateTo({
        url: '/' + advType.adv_uri + '?subject_id=' + subject_id,
      })
    }
  },
  /*红包广告跳转事件*/
  goAdvEvent: function (e) {
    var _this = this;
    var adv_solt = _this.data.adv_solt;
    if (_this.data.adv_solt) {
      //广告数据不为空
      if (adv_solt.adv_type == 1) {
        //图片类
        wx.navigateTo({
          url: '/pages/rule/rule?url=' + adv_solt.adv_info_url
        });
      } else if (adv_solt.adv_type == 3) {
        //小程序类
        wx.navigateToMiniProgram({
          appId: adv_solt.app_id.toString(),
          path: adv_solt.page.toString(),
          extraData: adv_solt.sence.toString(),
          complete(res) {
            console.log(res)
          }
        });
      } else {
        //内部网页类型
        wx.navigateTo({
          url: "/" + adv_solt.adv_uri,
        })
      }
    }
  },
  // 跳转商品详情页
  goDetail: function (e) {
    // console.log(e);
    var _this = this;
    var theGoodsId = e.currentTarget.dataset.goods_id;
    wx.navigateTo({
      url: '/pages/goodsDetail/goodsDetail?goodsId=' + theGoodsId,
    })
  },
  /*返回主页*/
  goHome: function () {
    wx.reLaunch({
      url: '/pages/home/home',
    })
  },
  ruleBtn: function () {
    var _this = this;
    // console.log("点");
    _this.setData({
      isResultMaskShow: 1
    });
  },
  closeRuleMask: function () {
    var _this = this;
    _this.setData({
      isResultMaskShow: 0
    });
  },
  // 获取活动规则数据
  getRuleData: function () {
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
    };
    app.post('/EnvePacket/rule', requestData, function (res) {
      if(res.code==2000){
      var theRuleList = res.data.list;
      _this.setData({
        ruleList: theRuleList
      })
      }else{
        wx.showToast({
          title: res.msg,
          icon: "none",
          duration: 2000
        });
      }
    })
  },
  // 获取热词文档列表
  getHotRecommend: function () {
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      keywords: _this.data.keywords,
      recommend_type:2,
      search_type:0,
      page: _this.data.page
    }
    app.post('/Goods/recommend', requestData, function (res) {
      if (res.code == 2000) {
        wx.hideNavigationBarLoading(); //完成停止加载
        wx.stopPullDownRefresh(); //停止下拉刷新
        var recommendList = _this.data.recommendList;

        recommendList = recommendList.concat(res.data.list);
        _this.setData({
          page: res.data.page,
          recommendList: recommendList
        })

      }else{
        wx.showToast({
          title: res.msg,
          icon: "none",
          duration: 2000
        });
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var _this = this;
    var scene = decodeURIComponent(options.scene);
    var configs = wx.getStorageSync('configs');
    _this.setData({
      sys_status: configs.sys_status,
      static_url_http:configs.static_url_http,
      enve_page_top_adv_is_show: configs.enve_page_top_adv_is_show,
      keywords: configs.key_words
    })
    if (scene && scene !== 'undefined') {
      console.log('我是从扫描二维码进来的');
      var sceneParams = new Array();
      sceneParams = scene.split('#');
      console.log(sceneParams);
      var uid = sceneParams[0];
      var enve_id = sceneParams[1];

      _this.setData({
        adv_info: adv_info,
        shareUid: uid,
        shareEnveId: enve_id,
      });
    } else if (options.uid && options.uid !== 'undefined') {
      _this.setData({
        adv_info: adv_info,
        shareUid: options.uid,
        shareEnveId: options.enve_id,
      });
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var _this = this;
    _this.loop();
    wx.getSystemInfo({
      success: function (res) {
        var theWinHeight = res.windowHeight;
        var theWinWidth = res.windowWidth;
        _this.setData({
          winWidth: theWinWidth,
          winHeight: theWinHeight
        });
      }
    });
  },
  // 判断是否获取到token的值了
  loop: function () {
    var _this = this;
    var theToken = wx.getStorageSync("token");
    if (!theToken) {
      setTimeout(function () { _this.loop() }, 100);
    } else {
      var configs = wx.getStorageSync('configs');
      _this.setData({
        token: theToken,
        filesSourceUri: configs.static_url_http,
      });
      _this.loadConfig();
      _this.enveInfo();
      _this.getRuleData();
      _this.getHotRecommend();
    }
  },
  /**
 * 加载初始化红包配置文件
 */
  loadConfig: function () {
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
    };
    app.post('/EnvePacket/enveConfig', requestData, function (res) {
      if (res.code == 2000) {
        console.log(res);
        _this.setData({
          isLoading:0,
          share_title: res.data.enve_share_title,
          title: res.data.title,
          content: res.data.tips,
          imgUrls: res.data.robot_list,
          playRobots: res.data.robot_list,
          successLeftTips: res.data.enve_success_left_tips,
          successRightTips: res.data.enve_success_right_tips,
          enve_share_info_title: res.data.enve_share_info_title,
          enve_share_info_border_tips: res.data.enve_share_info_border_tips,
          enve_goods_tip: res.data.enve_goods_tip,
          enve_box_title: res.data.enve_box_title,
          btnIsOk: 1
        });
      } else if (!res.code) {
        wx.showToast({
          title: '服务器去月球了',
          duration: 2000
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: "none",
          duration: 2000
        });
      }
    });
  },
  /**检测机器人数据是否播放完毕 */
  animationfinish: function (e) {
    var _this = this;
    if (_this.data.playRobots.length > 0) {
      var playRobots = _this.data.playRobots;
      playRobots.pop();
      _this.setData({
        playRobots: playRobots
      });
    } else {
      //数据播放完毕重新获取数据
      var requestData = {
        token: _this.data.token,
        version: app.setConfig.version,
      };
      app.post('/EnvePacket/getRobots', requestData, function (res) {
        if (res.code == 2000) {
          _this.setData({
            imgUrls: res.data.robot_list,
            playRobots: res.data.robot_list
          });
        } else if (!res.code) {
          wx.showToast({
            title: '服务器去月球了',
            duration: 2000
          })
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 2000
          });
        }
      });
    }
  },
  /**
   * 
   * 获取红包详情
   */
  enveInfo: function () {
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      enve_id: _this.data.enve_id,
    };
    var configs = wx.getStorageSync('configs');
    console.log(requestData);
    app.post('/EnvePacket/enveInfo', requestData, function (res) {
      console.log(res);
      if (res.code == 2000) {
        var adv_info = res.data.sub_adv;//导航列表
        var static_url_http = _this.data.static_url_http;
        for (var i = 0; i < adv_info.length; i++) {
          adv_info[i].adv_info_url = static_url_http + "/" + adv_info[i].adv_info_url;
        }
        _this.setData({
          adv_info: adv_info,//导航列表
          adv_solt: res.data.adv,
          shareUserList: res.data.share_user_list,
          successEnveNum: res.data.surplus_share_num,
          successEnve: res.data.enve_amount,
          balance: res.data.balance,
          is_opend: res.data.is_opend,
          uid: res.data.user_id,
          enve_id: res.data.enve_id,
          successLeftTips: res.data.enve_success_left_tips,
          successRightTips: res.data.enve_success_right_tips,
          shareFriendsBtn: res.data.share_group_btn,
          advSoltIcon: configs.static_url_http + "/" + res.data.adv.adv_info_url
        });
        if (res.data.group_share_num > 0) {
          _this.setData({
            successEnveNum: res.data.group_share_num
          });
        }
        if (res.data.group_share_isopen >= 0) {
          _this.setData({
            group_share_isopen: res.data.group_share_isopen,
            group_share_num: res.data.group_share_num
          });
        }
        if (res.data.packet_message_is_show == 1) {
          wx.showModal({
            title: '提示',
            content: res.data.packet_message,
            showCancel: false,
            confirmText: '确认',
            confirmColor: '#ff2e2e'
          })
        }
      } else if (!res.code) {
        wx.showToast({
          title: '服务器去月球了',
          duration: 2000
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: "none",
          duration: 2000
        });
      }
    });
  },

  //申请提现
  goWithdrawals: function () {
    wx.navigateTo({
      url: '/pages/enveWithdraw/enveWithdraw',
    })
  },
  goShare: function () {
    var _this = this;
    if (_this.data.enve_id) {
      wx.navigateTo({
        url: '../sharePacket/sharePacket?enve_id=' + _this.data.enve_id + "&uid=" + _this.data.uid,
      });
    } else {
      wx.showToast({
        title: '无法获取红包信息',
        duration: 2000,
        icon: "none"
      });
    }
  },
  /**红包打开后重新领取分享按钮 */
  goGainShareEvent: function () {
    var _this = this;
    if (_this.data.shareGainEnveId) {
      wx.navigateTo({
        url: '../sharePacket/sharePacket?enve_id=' + _this.data.shareGainEnveId + "&uid=" + _this.data.shareGainUid,
      });
    } else {
      wx.showToast({
        title: '无法获取红包信息',
        duration: 2000,
        icon: "none"
      });
    }
  },
  /*立即领取红包*/
  saveEnveEvent: function (e) {
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
    };
    app.post('/EnvePacket/createEnve', requestData, function (res) {
      if (res.code == 2000) {
        _this.setData({
          successGainTips: res.data.enve_success_tips,
          successGainEnve: res.data.enve_amount,
          successGainLeftTips: res.data.enve_success_left_tips,
          successGainLeftTopTips: res.data.gain_left_top_tips,
          successGainEnveNum: res.data.splus_num,
          successGainRightTips: res.data.enve_success_right_tips,
          shareGainUserList: res.data.share_user_list,
          isReceiveRedPacketShow: res.data.isReceiveRedPacketShow,
          shareGainEnveId: res.data.enve_id,
          shareGainUid: res.data.uid,
        });
        var openMessage = "";
        if (res.data.openMessage) {
          openMessage = res.data.openMessage;
        }
        if (res.data.uid != _this.data.shareUid && _this.data.shareUid != '' && typeof (_this.data.shareUid) != 'undefined') {
          //协助拆开红包
          var openShareData = {
            token: _this.data.token,
            version: app.setConfig.version,
            enve_id: _this.data.shareEnveId,
            uid: _this.data.shareUid
          }
          app.post('/EnvePacket/openEnve', openShareData, function (shareResult) {
            if(shareResult.code!=2000){
              wx.showToast({
                title: res.msg,
                icon: "none",
                duration: 2000
              });
            }
          });
        }
        if (res.data.isOpenTips == 1) {
          wx.showModal({
            title: '提示',
            content: openMessage,
            showCancel: false,
            confirmText: '确认',
            confirmColor: '#ff2e2e'
          })
        }
        _this.loop();
      } else if (!res.code) {
        wx.showToast({
          title: '服务器去月球了',
          duration: 2000
        })
      } else {
        wx.showToast({
          title: res.msg,
          duration: 2000
        })
      }
    });
  },
  /*下拉刷新事件*/
  onPullDownRefresh: function () {
    console.log('执行刷新情况');
    this.enveInfo();
    wx.stopPullDownRefresh();
  },
  /**
  * 页面上拉触底事件的处理函数
  */
  onReachBottom: function () {
    var _this = this;
    _this.getHotRecommend();
  },
  /**关闭closeUserListBoxEvent 弹层 */
  closeUserListBoxEvent: function () {
    var _this = this;
    _this.setData({
      userListBox: 0
    })
  },
  /**关闭拆红包弹窗 */
  closeReceiveRedPacket: function () {
    this.setData({
      isReceiveRedPacketShow: 0
    });
    //this.loop();
  },
  onReady: function () {
    wx.showShareMenu({
      withShareTicket: true
    })
  },
  // 分享执行
  onShareAppMessage: function (options) {
    var _this = this;
    if (options.from == "button") {
      return {
        title: _this.data.share_title,
        path: _this.data.share_path,
        imageUrl: _this.data.share_img,
        success: function (res) {
          wx.getShareInfo({
            shareTicket: res.shareTickets,
            success: function (res) {
              var requestData = {
                token: _this.data.token,
                version: app.setConfig.version,
                type: app.setConfig.type,
                encryptedData: res.encryptedData,
                iv: res.iv,
                enve_id: _this.data.enve_id
              }
              app.post('/EnvePacket/shareGroupSuccess', requestData, function (res) {
                if (res.code == 2000) {
                  console.log("传递的消息");
                  console.log(requestData);
                  console.log("返回的结果")
                  console.log(res);
                  if (_this.data.enve_id > 0) {
                    _this.setData({
                      is_opend: res.data.is_opend
                    });
                    _this.enveInfo();
                  } else {
                    _this.setData({
                      successGainTips: res.data.enve_success_tips,
                      successGainEnve: res.data.enve_amount,
                      successGainLeftTips: res.data.enve_success_left_tips,
                      successGainLeftTopTips: res.data.gain_left_top_tips,
                      successGainEnveNum: res.data.splus_num,
                      successGainRightTips: res.data.enve_success_right_tips,
                      shareGainUserList: res.data.share_user_list,
                      isReceiveRedPacketShow: res.data.isReceiveRedPacketShow,
                      shareGainEnveId: res.data.enve_id,
                      shareGainUid: res.data.uid,
                      successEnveNum: res.data.splus_num,
                      enve_id: res.data.enve_id,
                    });
                    var openMessage = "";
                    if (res.data.openMessage) {
                      openMessage = res.data.openMessage;
                    }
                    if (res.data.isOpenTips == 1) {
                      wx.showModal({
                        title: '提示',
                        content: openMessage,
                        showCancel: false,
                        confirmText: '确认',
                        confirmColor: '#ff2e2e'
                      })
                    }
                    _this.enveInfo();
                  }

                } else if (!res.code) {
                  wx.showToast({
                    title: '服务器去月球了',
                    duration: 2000
                  })
                } else {
                  wx.showToast({
                    title: res.msg,
                    icon: "none",
                    duration: 2000
                  });
                }
              });
            }
          })
        },
        fail: function (err) {
          console.log(err);
        }
      }
    }
  },
  /*切换显示群组分享界面*/
  showGroupShareEvent: function (e) {
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    _this.setData({
      is_opend: 0
    });
  }
})
